#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
系统配置文件
"""

import os
from pathlib import Path



RESULT = None # 全局变量

# 基础配置
BASE_DIR = Path(__file__).parent
LOG_DIR = BASE_DIR / "logs"
DATA_DIR = BASE_DIR / "data"

# 确保目录存在
LOG_DIR.mkdir(exist_ok=True)
DATA_DIR.mkdir(exist_ok=True)

# Flask应用配置 (APP.py)
FLASK_CONFIG = {
    "host": "0.0.0.0",
    "port": 5000,
    "debug": True,
    "allow_unsafe_werkzeug": True
}

# API服务器配置 (start_api_server2.py)
API_SERVER_CONFIG = {
    "host": "0.0.0.0",
    "port": 8001,
    "reload": True,
    "log_level": "info"
}

# Redis配置
REDIS_CONFIG = {
    "host": "localhost",
    "port": 6379,
    "db": 0,
    "password": None,
    "decode_responses": True
}

# 数据库配置
DATABASE_CONFIG = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "wzw123456",
    "database": "kylin_2025"
}

# SSH连接配置 (main.py)
SSH_CONFIG = {
    "host": "192.168.31.169",
    "username": "root",
    "private_key_path": r"C:\Users\32793\.ssh\id_rsa",
    "remote_workspace": "/opt/kylin_optimizer",
    "local_result_dir": "python/ansible-getsystem"
}

# Ansible脚本目录配置
ANSIBLE_CONFIG = {
    "scripts_dir": "agent-mcp/Ansible",
    "timestamp_format": "%Y%m%d%H%M%S"
}

# LLM配置
LLM_CONFIG = {
    "base_url": "http://10.11.5.14:11434",
    "model": "deepseek-r1:14b",
    "timeout": 60
}

# 服务启动配置
SERVICE_CONFIG = {
    "startup_delay": {
        "app_py": 5,      # Flask服务启动延迟
        "api_server2": 8,  # API服务器启动延迟
        "boss_node": 3,    # boss_node启动延迟
        "main_py": 3       # main.py启动延迟
    },
    "health_check": {
        "app_py": "http://localhost:5000/",
        "api_server2": "http://localhost:8001/health"
    },
    "monitor_interval": 10,  # 进程监控间隔(秒)
    "restart_timeout": 10    # 进程重启超时(秒)
}

# 日志配置
LOGGING_CONFIG = {
    "level": "INFO",
    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    "file": "all_main.log",
    "max_bytes": 10 * 1024 * 1024,  # 10MB
    "backup_count": 5
}

# 文件路径配置
FILE_PATHS = {
    "app_py": "APP.py",
    "api_server2": "start_api_server2.py",
    "boss_node": "Agent/nodes/boss_node.py",
    "main_py": "ansible_python/main.py",
    "test_script": "test_ansible_scripts.py",
    "debug_script": "debug_paths.py"
}

# 环境变量配置
ENV_VARS = {
    "PYTHONPATH": str(BASE_DIR),
    "FLASK_ENV": "development",
    "FLASK_DEBUG": "1"
}

def get_config():
    """获取完整配置"""
    return {
        "flask": FLASK_CONFIG,
        "api_server": API_SERVER_CONFIG,
        "redis": REDIS_CONFIG,
        "database": DATABASE_CONFIG,
        "ssh": SSH_CONFIG,
        "ansible": ANSIBLE_CONFIG,
        "llm": LLM_CONFIG,
        "service": SERVICE_CONFIG,
        "logging": LOGGING_CONFIG,
        "file_paths": FILE_PATHS,
        "env_vars": ENV_VARS
    }

def validate_config():
    """验证配置"""
    errors = []
    
    # 检查必要文件
    for name, path in FILE_PATHS.items():
        if not Path(path).exists():
            errors.append(f"文件不存在: {path}")
    
    # 检查目录
    if not Path(ANSIBLE_CONFIG["scripts_dir"]).exists():
        errors.append(f"Ansible脚本目录不存在: {ANSIBLE_CONFIG['scripts_dir']}")
    
    # 检查端口是否被占用
    import socket
    for service, config in [("Flask", FLASK_CONFIG), ("API Server", API_SERVER_CONFIG)]:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex(('localhost', config['port']))
            sock.close()
            if result == 0:
                errors.append(f"端口 {config['port']} 已被占用 ({service})")
        except Exception:
            pass
    
    return errors

def print_config():
    """打印配置信息"""
    print("=== 系统配置信息 ===")
    config = get_config()
    
    for section, settings in config.items():
        print(f"\n[{section.upper()}]")
        for key, value in settings.items():
            print(f"  {key}: {value}")
    
    # 验证配置
    errors = validate_config()
    if errors:
        print(f"\n❌ 配置验证失败:")
        for error in errors:
            print(f"  - {error}")
    else:
        print(f"\n✅ 配置验证通过")

if __name__ == "__main__":
    print_config() 